package com.example.marts.mobilelab3;

import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements SensorEventListener {

    //Sensor
    private SensorManager sensorManager;
    private Sensor gravitySensor;

    //The ball to move around on the screen
    private ImageView ball;
    private TextView tiltTextView;

    //The width of the frame
    private int frameWidth;
    //The height of the frame
    private int frameHeight;
    //Used to make the ball stay within the frame
    private int radius;

    //Used to play a sound when the ball hits the edge of the frame
    private ToneGenerator toneGenerator;

    //Gets the screens height and width
    DisplayMetrics displayMetrics;
    private int devHeight;
    private int devWidth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Gets the frame and the ball
        ImageView frame = findViewById(R.id.frame);
        ball = findViewById(R.id.ball);

        tiltTextView = findViewById(R.id.textview);

        //Initiates a new ToneGenerator
        toneGenerator = new ToneGenerator(AudioManager.STREAM_MUSIC, ToneGenerator.MAX_VOLUME);

        //Sets the height and with of the frame
        frameWidth = frame.getWidth();
        frameHeight = frame.getHeight();

        //Sets the radius
        radius = 25;

        //Gets the system sensors
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        assert sensorManager != null;
        //Selects the gravitySensor sensor
//        gravitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);

        gravitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

        magnetometer = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);

        //Gets the screens height and width
        displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        devHeight = displayMetrics.heightPixels;
        devWidth = displayMetrics.widthPixels;

        //Creates a listener on the sensor
        sensorManager.registerListener(this, gravitySensor, SensorManager.SENSOR_DELAY_GAME);
        //Set the delay to GAME as that created a less "laggy" experience


        ball.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainActivity.this, MainActivityTest2.class));
            }
        });

    }


    private float minHeight = 100; // 小球的最小高度
    private float maxHeight = 800; // 小球的最大高度
    private float speed = 5f; // 小球移动的速度
    private float currentHeight = 500; // 小球的当前高度
    private float initBallViewHeight = 500; // 小球的当前高度
    private boolean moveUp = true; // 用于控制小球移动方向的标志位

    private Sensor magnetometer;
    private float[] gravity;
    private float[] geomagnetic;

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            gravity = sensorEvent.values;
        }
        if (sensorEvent.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
            geomagnetic = sensorEvent.values;
        }
        if (gravity != null && geomagnetic != null) {
            float R[] = new float[9];
            float I[] = new float[9];
            boolean success = SensorManager.getRotationMatrix(R, I, gravity, geomagnetic);
            if (success) {
                float orientation[] = new float[3];
                SensorManager.getOrientation(R, orientation);

                float pitch = (float) Math.toDegrees(orientation[1]); // 倾斜角度，绕x轴
                float abs = Math.abs(pitch);

                String tiltInfo = String.format("Pitch: %.2f°", abs);
                tiltTextView.setText(tiltInfo);

                // 倾斜角与圆球处于正中心的 50度的差值
                float charValue = abs - 50;
                dealBallMove(charValue, sensorEvent);
            }
        }


//        initBallMove(sensorEvent);

//        float z = sensorEvent.values[1];
//
//        float moveSensorEvent = z;
//
//        moveUp = z > 0;
//        Log.d("rogerzhang", moveSensorEvent + "=-------1111111----" + currentHeight);
//
//        // 根据手机的倾斜程度控制小球运动的方向
//        if (moveUp) {
//            if (currentHeight >= maxHeight) {
//                currentHeight = maxHeight - 25;
//            }
//
//            if (currentHeight > minHeight) {
//                currentHeight -= speed * z;
//            }
//            Log.d("rogerzhang", "2222222----" + currentHeight);
//            if (currentHeight <= minHeight) {
//                currentHeight = minHeight;
////                moveUp = false;
//            }
//        } else {
//            if (currentHeight <= minHeight) {
//                currentHeight = minHeight;
//            }
//
//            if (currentHeight < maxHeight) {
//                currentHeight -= speed * z;
//            }
//
//            Log.d("rogerzhang", "3333333----" + currentHeight);
//            if (currentHeight >= maxHeight) {
//                currentHeight = maxHeight;
////                moveUp = true;
//            }
//        }
//
//        // 更新小球的位置
//        ball.setY(currentHeight);
    }

//    private void initBallMove(SensorEvent sensorEvent) {
//                float z = sensorEvent.values[1];
//
//        float moveSensorEvent = z;
//
//        moveUp = z > 0;
//        Log.d("rogerzhang", moveSensorEvent + "=-------1111111----" + currentHeight);
//
//        // 根据手机的倾斜程度控制小球运动的方向
//        if (moveUp) {
//            if (currentHeight >= maxHeight) {
//                currentHeight = maxHeight - 25;
//            }
//
//            if (currentHeight > minHeight) {
//                currentHeight -= speed * z;
//            }
//            Log.d("rogerzhang", "2222222----" + currentHeight);
//            if (currentHeight <= minHeight) {
//                currentHeight = minHeight;
////                moveUp = false;
//            }
//        } else {
//            if (currentHeight <= minHeight) {
//                currentHeight = minHeight;
//            }
//
//            if (currentHeight < maxHeight) {
//                currentHeight -= speed * z;
//            }
//
//            Log.d("rogerzhang", "3333333----" + currentHeight);
//            if (currentHeight >= maxHeight) {
//                currentHeight = maxHeight;
////                moveUp = true;
//            }
//        }
//
//        // 更新小球的位置
//        ball.setY(currentHeight);
//    }

    private void dealBallMove(float charValue, SensorEvent sensorEvent) {
//        float z = sensorEvent.values[1];
       float z = charValue;
        moveUp = z > 0;


        int moveSize = (int)z;

        Log.d("rogerzhang", z + "=-------1111111----" + currentHeight);

        currentHeight = initBallViewHeight +(speed * moveSize);

        Log.d("rogerzhang", z + "=--------moveSize--"+ moveSize + "-----2222222----" + currentHeight);
//        if (moveUp) { // 向上移动。
//
//                currentHeight = initBallViewHeight +(speed * moveSize);
//
//            Log.d("rogerzhang", "2222222----" + currentHeight);
//
//        } else { // 向下移动。
//            if (currentHeight <= minHeight) {
//                currentHeight = minHeight;
//            }
//            if (currentHeight < maxHeight) {
//                currentHeight -= speed * z;
//            }
//            Log.d("rogerzhang", "3333333----" + currentHeight);
//            if (currentHeight >= maxHeight) {
//                currentHeight = maxHeight;
//            }
//        }

        // 根据手机的倾斜程度控制小球运动的方向
//        if (moveUp) { // 向上移动。
//            if (currentHeight >= maxHeight) {
//                currentHeight = maxHeight - 25;
//            }
//
//            if (currentHeight > minHeight) {
//                currentHeight -= speed * z;
//            }
//            Log.d("rogerzhang", "2222222----" + currentHeight);
//            if (currentHeight <= minHeight) {
//                currentHeight = minHeight;
//            }
//        } else { // 向下移动。
//            if (currentHeight <= minHeight) {
//                currentHeight = minHeight;
//            }
//            if (currentHeight < maxHeight) {
//                currentHeight -= speed * z;
//            }
//            Log.d("rogerzhang", "3333333----" + currentHeight);
//            if (currentHeight >= maxHeight) {
//                currentHeight = maxHeight;
//            }
//        }

        // 更新小球的位置
        ball.setY(currentHeight);
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {
        //NOT USED, but implemented as SensorEventListener needs it
    }

    @Override
    protected void onResume() {
        super.onResume();
        //Creates a listener on the gravity-sensor on resuming the app
        sensorManager.registerListener(this, gravitySensor, SensorManager.SENSOR_DELAY_GAME);
//        sensorManager.registerListener(this, gravitySensor, SensorManager.SENSOR_DELAY_UI);

        sensorManager.registerListener(this, magnetometer, SensorManager.SENSOR_DELAY_UI);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //Removes the listener when the app is not in use
        sensorManager.unregisterListener(this);
    }

    /**
     * Sets of multiple effects when the ball hits the edge of the frame
     */
    private void onFrameHit() {
        //Vibrator
//        Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
//        assert vibrator != null;
//        vibrator.vibrate(400);

        //Sound
//        toneGenerator.startTone(ToneGenerator.TONE_CDMA_ONE_MIN_BEEP);
    }
}
